<?php

namespace app\data\controller;

use app\data\controller\base\Publics;
use think\Db;
use think\Log;

/**
 * 活动 
 * Class Activity
 * @package app\data\controller
 */
class Activity
{

	/**
	 * 实例对象
	 * @var object
	 */
	protected static $instance;

	/**
	 * 表
	 * @var  Publics::instance()->tab();
	 */
	protected $tab = null;

	public function __construct()
	{
		$this->tab = Publics::instance()->tab();
	}

	/**
	 * 实例化
	 * @var object
	 */
	public static function instance()
	{
		if (is_null(self::$instance)) {

			self::$instance = new static();
		}
		return self::$instance;
	}

	/**
	 * 新人有礼活动达标金额计算
	 */
	public function newlyTakes($sn, $money, $time)
	{
		try {
			$binds = Publics::instance()->snBinds($sn);
			if ($binds) {
				if ($binds["uid"]) {
					$take = Db::name($this->tab->take)
						->field("id,start,ends,standsAmt,tranAmt,is_stands")
						->where("uid", $binds["uid"])->where(["active_typs" => 1, "is_due" => 2, "is_stands" => 2])
						->find();
					if ($take) {
						$update = [];
						$is_due	= 2;
						$is_stands = 2;
						$upAmt = $take["tranAmt"];
						$time = strtotime(date("Y-m-d", $time));
						if ($time > $take["ends"]) {
							$is_due = 1;
						} else {
							if ($time >= $take["start"] && $time <= $take["ends"]) {
								$upAmt = bcadd((string)$take["tranAmt"], (string)$money, 2);
								if (intval($upAmt) >= intval($take["standsAmt"])) {
									$is_stands = 1;
									$update["stands_time"] = time();
								}
							}
						}
						$update["tranAmt"] = $upAmt;
						$update["is_stands"] = $is_stands;
						$update["is_due"] = $is_due;
						$update["update_time"] = time();
						Db::name($this->tab->take)->where("id", $take["id"])->update($update);
					}
				}
			}
		} catch (\Exception $e) {
			Log::write($e->getMessage());
		}
	}
}
